﻿
namespace Mulala.Cavan.Presentation.Mvc.Controller
{
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Mulala.Cavan.Application.MainBoundedContext.MulalaModule;
    using Mulala.Cavan.Application.MainBoundedContext.SecurityModule;
    using Mulala.Cavan.Core.Extension;
    using Mulala.Cavan.Core.Message;
    using Mulala.Cavan.Domain.MainBoundedContext.MulalaModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SearchModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SecurityModule;
    using Mulala.Cavan.Presentation.Mvc.ViewModel;
    using Mulala.Cavan.Presentation.Seedwork;
    using Mulala.Cavan.Domain.MainBoundedContext.Setting;
    using Mulala.Cavan.Domain.Seedwork;
    using Mulala.Cavan.Core.Cryptography;

    public class UserAccountController : EntityController<UserAccount, UserAccountSearch, IUserAccountViewModel, IUserAccountAppService>, IUserAccountController
    {
        private IRoleAppService RoleAppService { get; set; }
        private IMulalaRegistrationAppService MulalaRegistrationAppService { get; set; }

        public UserAccountController()
        {
            this.Model = ModelFactory.CreateModel<IUserAccountViewModel>();
        }

        #region properties
        public override string ControllerName
        {
            get { return ControllerConst.USERACCOUNT; }
        }

        public override bool UseDenied
        {
            get { return false; }
        }
        #endregion properties

        #region actions
        [ActionName("login")]
        [HttpGet]
        public ActionResult LogOn()
        {
            return View();
        }

        [ActionName("login")]
        [HttpPost]
        public ActionResult LogOn(UserAccountViewModel model)
        {
            string returnUrl = string.Empty;
            if (!this.HttpContext.Request["returnUrl"].IsNull())
            {
                returnUrl = this.HttpContext.Request["returnUrl"].ToString();
            }
            if (returnUrl.IsNotEmpty() && !returnUrl.Contains(Project.Settings.HostServer))
            {
                returnUrl = Project.Settings.HostServer + returnUrl;
            }

            UserAccountSearch userAccountSearch = UserAccountSearchFactory.CreateUserAccountSearch(model.Item.LoginName);
            UserAccount loginUserAccount = this.AppService.GetSingleBySearch(userAccountSearch);
            if (loginUserAccount != null)
            {
                if (loginUserAccount.Password != Crypto.Encrypt(model.Item.Password))
                {
                    Model.Messages.AddError(this, "PasswordError",
                        "密码不正确，请重新输入！", null);
                }
                else
                {
                    FormAuthenticationService.SignIn(model.Item.LoginName, true);
                    if (returnUrl.IsNotEmpty())
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("index", "home");
                    }
                }
            }
            else
            {
                Model.Messages.AddError(this, "UserAccountNotExist",
                    "用户帐号{0}不存在,请检查后重新输入！", model.Item.LoginName);
            }
            model.Messages = Model.Messages;
            return View(model);
        }

        [ActionName("logoff")]
        public ActionResult LogOff()
        {
            FormAuthenticationService.SignOut();
            return RedirectToAction("index", ControllerConst.HOME);
        }

        [ActionName("logincn")]
        [HttpGet]
        public ActionResult LogonByNannyOrCorporation()
        {
            return View();
        }

        [ActionName("logincn")]
        [HttpPost]
        public ActionResult LogonByNannyOrCorporation(UserAccountViewModel model)
        {
            return View(model);
        }

        [ActionName("register")]
        [HttpGet]
        public ActionResult AddUserAccount()
        {
            IUserAccountViewModel model = ModelFactory.CreateModel<IUserAccountViewModel>();
            model.Item = new UserAccount();

            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "业主", Value = SecurityIdentifier.Role.Proprietor.GetHashCode().ToString(), Selected = true });
            items.Add(new SelectListItem { Text = "家政人员", Value = SecurityIdentifier.Role.Nanny.GetHashCode().ToString() });
            items.Add(new SelectListItem { Text = "家政公司", Value = SecurityIdentifier.Role.Corporation.GetHashCode().ToString() });
            ViewBag.Roles = items;

            return View(model);
        }

        [HttpGet]
        public ActionResult CheckUserAccountExists(string name)
        {
            name = this.Request.QueryString[0];
            UserAccountSearch search = UserAccountSearchFactory.CreateUserAccountSearch(name);
            UserAccount userAccount = this.AppService.GetSingleBySearch(search);

            bool exists = null != userAccount ? true : false;
            return Json(!exists, JsonRequestBehavior.AllowGet);
        }

        [ActionName("register")]
        [HttpPost]
        public ActionResult AddUserAccount(UserAccountViewModel userAccount)
        {
            if (userAccount.RegisterRoleID == SecurityIdentifier.Role.Proprietor.GetHashCode())
            {
                ProprietorRegistrationResult result = this.MulalaRegistrationAppService.AddProprietor(userAccount.Item.Name, userAccount.Item.Password, userAccount.Item.Email, Project.Settings.DefaultArea.ID);
                if (result.IsSuccess)
                {
                    RedirectToAction("info", ControllerConst.PROPRIETORCENTER);
                }
            }
            else if (userAccount.RegisterRoleID == SecurityIdentifier.Role.Nanny.GetHashCode())
            {
                NannyRegistrationResult result = this.MulalaRegistrationAppService.AddNanny(userAccount.Item.Name, userAccount.Item.Password, userAccount.Item.Email, Project.Settings.DefaultArea.ID);
                if (result.IsSuccess)
                {
                    RedirectToAction("info", ControllerConst.NANNYCENTER);
                }
            }
            else if (userAccount.RegisterRoleID == SecurityIdentifier.Role.Corporation.GetHashCode())
            {
                CorporationRegistrationResult result = this.MulalaRegistrationAppService.AddCorporation(userAccount.Item.Name, userAccount.Item.Password, userAccount.Item.Email, Project.Settings.DefaultArea.ID);
                if (result.IsSuccess)
                {
                    RedirectToAction("info", ControllerConst.CORPORATIONCENTER);
                }
            }

            return RedirectToAction("index", ControllerConst.HOME);
        }

        [ActionName("changepassword")]
        public ActionResult ChangePassword()
        {
            return View();
        }
        #endregion

    }
}
